from basedata.models import City
from django import template

register = template.Library()


# 州的下拉菜单列表展示
def state(id):
    select = '<div class=\'col-md-3\'><select class="form-control" id="state" name="state_name">'
    select += '<option value="0">州</option>'
    for area in City.objects.filter(parent_id=None):
        if id == area.id:
            select += '<option selected=\'selected\' value="' + str(area.id) + '">' + area.state_name + '</option>'
        else:
            select += '<option value="' + str(area.id) + '">' + area.state_name + '</option>'
    select += '</select></div>'
    return select


# 市的下拉菜单列表展示 parent表示父类id
def city(parent_id, id=0):
    select = '<div class=\'col-md-3\'><select class="form-control" id="city" name="city_name">'
    select += '<option value="0">市</option>'
    select += city_tags('C', parent_id, id)  # 调用增加选项方法
    select += '</select></div>'
    return select


# 区的下拉菜单列表展示 parent表示父类id
def area(parent_id, id=0):
    select = '<div class=\'col-md-3\'><select class="form-control" id="area" name="area_name">'
    select += '<option value="0">区</option>'
    select += city_tags('A', parent_id, id)  # 调用增加选项方法
    select += '</select></div>'
    return select


# 三级下拉级联菜单展示  type表示级别类型  id 表示pk
@register.simple_tag
def city_tag(type, id):
    if type == 'S':
        select_state = state(id)
        select_city = city(id)
        select_area = area(0)
    elif type == 'C':
        city_now = City.objects.filter(id=id)
        select_state = state(city_now[0].parent_id)
        select_city = city(city_now[0].parent_id, id)
        select_area = area(id)
    else:
        area_now = City.objects.filter(id=id)
        select_state = state(area_now[0].parent.parent_id)
        select_city = city(area_now[0].parent.parent_id, area_now[0].parent_id)
        select_area = area(area_now[0].parent_id, id)
    return select_state + select_city + select_area


def city_tags(type, parent_id, id=0):
    if type == 'C':
        select = ''
        for area in City.objects.filter(parent_id=parent_id):
            if id == area.id:
                select += '<option selected=\'selected\' value="' + str(
                    area.id) + '">' + area.city_name + '</option>'
            else:
                select += '<option value="' + str(area.id) + '">' + area.city_name + '</option>'
        return select
    else:
        select = ''
        for area in City.objects.filter(parent_id=parent_id):
            if id == area.id:
                select += '<option selected=\'selected\' value="' + str(
                    area.id) + '">' + area.area_name + '</option>'
            else:
                select += '<option value="' + str(area.id) + '">' + area.area_name + '</option>'
    return select
